<?php

namespace App\Http\BackendControllers;


use App\Models\Permission;
use App\Models\Role;
use App\Services\RoleService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RoleController extends Controller
{

    public function index()
    {
        $data = Role::with('permissions')->paginate(6);
        $permissions = Permission::all();
        return view('backend.role.index', compact('data','permissions'));
    }

    public function store(Request $request){
        $data = $request->only('name','description');
        $permissions = $request->input('permissions');
        $role_id = $request->input('id');
        $rules = [
            'name' => 'required',
            'description' => 'required'
        ];
        $message = [
            'name' => "角色不能为空",
            'description' => '描述不能为空'
        ];
        $validator = Validator::make($data,$rules,$message);
        if($validator->fails()){
            return err('',$validator->errors()->first());
        }
        if($role_id){
            $role = Role::where('id',$role_id)->first();
            $role->update($data);
            RoleService::rolePremission($role,$permissions);
        }else{
            $role = Role::create($data);
            $role->permissions()->attach($permissions);
        }
        return res('','提交成功');
    }

    public function destroy(Request $request){
        $id = $request->only('id');
        $role = Role::where('id',$id)->first();
        $role->permissions()->detach();
        $role->delete();
        return res('','删除成功');
    }







}
